import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { Scrollbars } from 'react-custom-scrollbars'
import { Tag } from 'antd'
import { HomeOutlined } from '@ant-design/icons'
import classnames from 'classnames'
import { deleteTag, emptyTaglist, closeOtherTags } from '@/store/actions'

class TagList extends Component {
  handleChange() {
  }

  handleClose(tag) {
    const { history, deleteTag, tagList } = this.props
    const { path } = tag
    const currentPath = history.location.pathname
    const { length } = tagList
    const lastTagPath = tagList[length - 1] && tagList[length - 1].path
    // debugger

    if (path === currentPath) {
      // 处理关闭当前标签
      if (currentPath !== lastTagPath) {
        history.push(lastTagPath)
      } else {
        // 处理关闭最后一个
        if (length > 2) {
          history.push(tagList[length - 2].path)
        }
        if (length === 2) {
          history.push(tagList[0].path)
        }
      }
    }

    deleteTag(tag)
  }

  handleClick(path) {
    const { history } = this.props
    history.push(path)
  }

  render() {
    const { tagList, history } = this.props
    const currentPath = history.location.pathname
    const homePath = '/dashboard'

    return (
      <>
        <Scrollbars autoHide autoHideTimeout={1000} autoHideDuration={200} hideTracksWhenNotNeeded>
          <ul className="tags-wrap">
            {tagList.map((tag) => (
              <li
                key={tag.path}
                className={classnames({
                  'tag-active': currentPath === tag.path,
                  'tag-home': homePath === tag.path,
                })}
              >
                <Tag
                  onClose={this.handleClose.bind(this, tag)}
                  closable={tag.path !== homePath}
                  onClick={this.handleClick.bind(this, tag.path)}
                >
                  {tag.path === homePath ? <HomeOutlined /> : tag.title}
                </Tag>
              </li>
            ))}
          </ul>
        </Scrollbars>
      </>
    )
  }
}

export default withRouter(connect((state) => state.tagsView, { deleteTag, emptyTaglist, closeOtherTags })(TagList))
